package com.starblink.wishlist.wishlistdetails.ui.part

import android.graphics.Color
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.animators.FadeInAnimator
import com.starblink.android.basic.ext.bindProductFeeds
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.style.databinding.BaseLayoutEmptyWishTemplateBinding
import com.starblink.basic.style.view.round.CornerType
import com.starblink.basic.util.CommUtils
import com.starblink.library.widget.databinding.CellSimpleProductCardBinding
import com.starblink.wishlist.databinding.ActivityWishlistDetailsBinding
import com.starblink.wishlist.databinding.ItemBoardDetailsChildBinding
import com.starblink.wishlist.databinding.LayoutRelatedTitleBinding
import com.starblink.wishlist.wishboards.ui.cells.BoardRelatedTitleCell
import com.starblink.wishlist.wishboards.ui.cells.WishProductCell
import com.starblink.wishlist.wishlistdetails.ui.WishlistDetailsVM
import com.starblink.wishlist.wishlistdetails.ui.bean.RvBoardDetailsItemEntry
import com.starblink.wishlist.wishlistdetails.ui.cells.BoardDetailsItemsCell
import com.starblink.wishlist.wishlistdetails.ui.cells.EmptyBoardDetailsCell

class WishDetailsPart(
    var isSelf: Boolean,
    var wishListId: String,
    var viewBinding: ActivityWishlistDetailsBinding,
    var viewModel: WishlistDetailsVM
) {
    var layoutManager: StaggeredGridLayoutManager? = null
    private var mutiItemNumSuffix =
        CommUtils.getString(com.starblink.basic.style.R.string.items_selected)

    private val wishlistDetailsAdapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.mAllItemsObserver.value!!).apply {
            //类目
            addVhDelegate {
                EmptyBoardDetailsCell(
                    BaseLayoutEmptyWishTemplateBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                BoardDetailsItemsCell(
                    ItemBoardDetailsChildBinding.inflate(it.inflater, it, false),
                    spmPageValue = if (isSelf) SpmPageDef.WishListRoute else SpmPageDef.Page_10214,
                    wListId = viewModel.mWishlistId,
                    isSelf = isSelf,
                    deleteClickCallback = { bean ->
                        //取消收藏
                        viewModel.mAllItemsObserver.value!!.remove(bean)
//                        wishlistDetailsAdapter.notifyItemRemoved(removePosition)
                        viewModel.mAllItemsObserver.postValue(viewModel.mAllItemsObserver.value)
                        FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_DETAILS_ITEMS_NUM)
                    },
                    choiceClickCallback = { position, isChoice ->
                        //左侧选择点击
                        var entry =
                            viewModel.mAllItemsObserver.value!![position] as RvBoardDetailsItemEntry
                        entry.hasChoice = isChoice
                        notifyItemChanged(position)
                        //如果有一个没选 全选置为false
                        if (!isChoice) {
                            viewModel.selectAll = false
                        } else {
                            var allSelect = true
                            for (item in viewModel.mAllItemsObserver.value!!) {
                                if (item is RvBoardDetailsItemEntry) {
                                    allSelect = allSelect && item.hasChoice
                                    if (!allSelect) {
                                        break
                                    }
                                }
                            }
                            viewModel.selectAll = allSelect
                        }
                        //取消或选中一个item
                        switchAllChoiceImg(false, 2)
                    }
                )
            }
            addVhDelegate {
                BoardRelatedTitleCell(
                    LayoutRelatedTitleBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                WishProductCell(
                    refreshLayout = viewBinding.page,
                    recyclerView = viewBinding.rv,
                    wishListId = wishListId,
                    binding = CellSimpleProductCardBinding.inflate(it.inflater, it, false),
                    spmPageValue = SpmPageDef.Page_10172,
                    cardClick = { model, position ->
                    }
                )
            }
        }
    }

    fun handleVM() {
        layoutManager =
            viewBinding.rv.bindProductFeeds(
                wishlistDetailsAdapter, horGap = 11,
                verGap = 10
            ) as StaggeredGridLayoutManager?
        viewBinding.rv.itemAnimator = FadeInAnimator()
        viewBinding.rv.isNestedScrollingEnabled = true

//        viewBinding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
//            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
//                super.onScrolled(recyclerView, dx, dy)
////                if (!viewBinding.rv.canScrollVertically(1)) {
////                    //滑动到底部
////                }
//                if (!viewBinding.rv.canScrollVertically(-1)) {
//                    //滑动到顶部
//                    if (viewModel.chongpai) {
//                        wishlistDetailsAdapter.notifyItemRangeChanged(
//                            0,
//                            wishlistDetailsAdapter.itemCount
//                        )
//                        viewModel.chongpai = false
//                    }
//                }
//            }
//        })

    }

    fun dataChange(it: ArrayList<Any>) {
        wishlistDetailsAdapter.refreshAll()
        wishlistDetailsAdapter.notifyItemRangeChanged(0, wishlistDetailsAdapter.itemCount)
        //数据改变了 刷新一次状态
        switchAllChoiceImg(false, 2)
    }


    fun getAdapter(): MutableAdapter {
        return wishlistDetailsAdapter
    }


    fun mutiChange(sMode: Boolean) {
        viewModel.choiceMode = sMode
        if (sMode) {
            viewModel.clearChoiceHistory()
            //刷底部显示
            switchAllChoiceImg(false, 2)
            //底部多选出现
            viewBinding.llMutiBtmLay.visible()
        } else {
            viewBinding.llMutiBtmLay.gone()
        }
        changeRvDataAll(selectAllOrReverse = false)
    }


    private fun changeRvDataAll(selectAllOrReverse: Boolean) {
        if (viewModel.mAllItemsObserver.value!!.isNotEmpty()) {
            viewModel.mAllItemsObserver.value!!.forEach {
                if (it is RvBoardDetailsItemEntry) {
                    it.showCheckMode = viewModel.choiceMode
                    if (selectAllOrReverse) {
                        it.hasChoice = viewModel.selectAll
                    } else {
                        it.hasChoice = false
                    }
                }
            }
            wishlistDetailsAdapter.notifyDataSetChanged()
        }
    }


    /**
     * 所有底部的变化都在这个方法里写
     * @param totalNumTxtType   1 全选模式 | 2 遍历
     * @param change 是否刷新所有items
     */
    fun switchAllChoiceImg(selectAllOrReverse: Boolean, totalNumTxtType: Int) {
        if (selectAllOrReverse) {
            viewModel.selectAll = !viewModel.selectAll
            changeRvDataAll(selectAllOrReverse = true)
        }

//        YYLogUtils.e("--------------viewModel.selectAll${viewModel.selectAll}------------------")
        if (viewModel.selectAll) {
            viewBinding.mutiAllChoice.setImageDrawable(CommUtils.getDrawable(com.starblink.basic.style.R.drawable.ic_checkbox_true))
        } else {
            viewBinding.mutiAllChoice.setImageDrawable(CommUtils.getDrawable(com.starblink.basic.style.R.drawable.ic_checkbox_false))
        }

        when (totalNumTxtType) {
            //1 不适应普遍的情况 限制条件多 不利于扩展
//            1 -> {
//                val num = viewModel.getChoiceNum(viewModel.selectAll)
//                viewBinding.mutiChoiceTotalNum.text =
//                    "${num} $mutiItemNumSuffix"
//            }
            2 -> {
                val num = viewModel.refreshChoiceNum()
                viewBinding.mutiChoiceTotalNum.buildSpannableString {
                    if (num == 0) {
                        addText("0") {
                            setColor(Color.parseColor("#64748B"))
                        }
                    } else {
                        addText("$num") {
                            setColor(Color.parseColor("#E11D48"))
                        }
                    }
                    addText(" $mutiItemNumSuffix") {
                        setColor(Color.parseColor("#64748B"))
                    }
                }
            }
        }
        //处理底部两个按钮

        if (viewModel.choiceNum > 0) {
            viewBinding.mutiAllChoiceDel.setCornerRadius(
                CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600).toFloat(),
                CornerType.R_BORDER_COLOR
            )
            viewBinding.mutiAllChoiceDelTxt.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600))
            viewBinding.mutiAllChoiceAdd.setBackgroundResource(com.starblink.basic.style.R.color.sk_red600)
        } else {
            viewBinding.mutiAllChoiceDel.setCornerRadius(
                CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600_opacity50).toFloat(),
                CornerType.R_BORDER_COLOR
            )
            viewBinding.mutiAllChoiceDelTxt.setTextColor(CommUtils.getColor(com.starblink.basic.style.R.color.sk_red600_opacity50))
            viewBinding.mutiAllChoiceAdd.setBackgroundResource(com.starblink.basic.style.R.color.sk_red600_opacity50)
        }
    }


}